//
//  MovieDetaiVC.m
//  OpenEyes
//
//  Created by dlios on 15/9/21.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "MovieDetaiVC.h"
#import "PlayMovieVC.h"
#import "MovieDetailCell.h"
#define MDcollReuse @"collReuse"
#import "CoreDataManager.h"
#import "VideoModel.h"
@interface MovieDetaiVC ()<UICollectionViewDataSource, UICollectionViewDelegate>
@property(nonatomic, strong)NSMutableArray *movieDetaiArr;
@property(nonatomic, strong)UICollectionView *collView;

@property(nonatomic, strong)UIView *downBackView;
@property(nonatomic, strong)UIView *downSecondView;
@property(nonatomic, strong)UILabel *downTitleLabel;
@property(nonatomic, strong)UILabel *downTimeLabel;
@property(nonatomic, strong)UILabel *downDetailLabel;
@property(nonatomic, assign)CGFloat scrollerOffset;
@property(nonatomic, strong)UIButton *saveButton;
@property(nonatomic, strong)UIButton *downLoadButton;
@property(nonatomic, strong)UILabel *showPrograss;

@property(nonatomic, strong)MPMoviePlayerViewController *player;

@property(nonatomic, strong)CoreDataManager *manager;


@end

@implementation MovieDetaiVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.manager = [CoreDataManager shareCoreDataManager];
    self.movieDetaiArr = [NSMutableArray array];
    self.movieDetaiArr = self.dailyListArr[self.movieIndexPath.section];
    self.scrollerOffset = WIDTH * self.movieIndexPath.row;
    [self creatTopViewForDetail];
    [self createMovieDetaiView];
    [self addGesture];

}
#pragma mark - 创建界面
- (void)createMovieDetaiView
{
    //    渐变视图
    self.downBackView = [[UIView alloc] initWithFrame:CGRectMake( 0, (HEIGHT - 64)/2 + 64, WIDTH, (HEIGHT - 64)/2)];
    [self.view addSubview:self.downBackView];
    VideoModel *mod = self.movieDetaiArr[self.movieIndexPath.row];
    for (NSInteger i = 2;  i >= 0; i--) {
        UIImageView *aView = [[UIImageView alloc] initWithFrame:self.downBackView.bounds];
        [aView sd_setImageWithURL:[NSURL URLWithString:mod.coverBlurred] placeholderImage:[UIImage imageNamed:@"placehoder"]];
        aView.tag = 1000 + i;
        [self.downBackView addSubview:aView];
    }
    VideoModel *model = self.movieDetaiArr[self.movieIndexPath.row];
    self.leftBuName.text = [model.date substringWithRange:NSMakeRange(2, 6)];
    self.leftBuName.font = [UIFont fontWithName:@"AmericanTypewriter" size:13];
    //    黑色效果
    UIView *blackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, (HEIGHT - 64)/2 )];
    blackView.backgroundColor = [UIColor blackColor];
    blackView.alpha = 0.5;
    [self.downBackView addSubview:blackView];
    
    self.downSecondView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, (HEIGHT - 64)/2)];
    [self.downBackView addSubview:self.downSecondView];
    
    
    
    self.downTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, WIDTH - 10, 30)];
    self.downTitleLabel.text = model.title;
    self.downTitleLabel.textColor = [UIColor whiteColor];
    [self.downSecondView addSubview:self.downTitleLabel];
    
    self.downTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, WIDTH - 10, 25)];
    self.downTimeLabel.text = [NSString stringWithFormat:@"%@ / %@", model.category, model.duration];
    self.downTimeLabel.textColor = [UIColor whiteColor];
    [self.downSecondView addSubview:self.downTimeLabel];
    
    self.downDetailLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 55, WIDTH - 20, 100)];
    self.downDetailLabel.text = model.myDescription;
    self.downDetailLabel.textColor = [UIColor whiteColor];
    self.downDetailLabel.numberOfLines = 0;
    self.downDetailLabel.font = [UIFont systemFontOfSize:12];
    [self.downSecondView addSubview:self.downDetailLabel];
    
    self.saveButton = [[UIButton alloc] initWithFrame:CGRectMake(10, self.downSecondView.frame.size.height - 50, 50, 20)];
    self.saveButton.backgroundColor = [UIColor clearColor];
    [self.saveButton setImage:[UIImage imageNamed:@"shoucang"] forState:UIControlStateNormal];
    if ([self.manager selectData:model.title EntityStyle:Save].count != 0) {
        [self.saveButton setImage:[UIImage imageNamed:@"shoucang(1)"] forState:UIControlStateNormal];
    }
    self.saveButton.imageView.contentMode = 1;
    [self.saveButton addTarget:self action:@selector(clicksaveButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.downSecondView addSubview:self.saveButton];
    
//    self.downLoadButton = [[UIButton alloc] initWithFrame:CGRectMake(60, self.downSecondView.frame.size.height - 50, 50, 20)];
//    self.downLoadButton.backgroundColor = [UIColor clearColor];
//    [self.downLoadButton setImage:[UIImage imageNamed:@"xiazai"] forState:UIControlStateNormal];
//    if ([self.manager selectData:model.title EntityStyle:DownLoad].count != 0) {
//        [self.downLoadButton setImage:[UIImage imageNamed:@"xiazai(1)"] forState:UIControlStateNormal];
//    }
//    self.downLoadButton.imageView.contentMode = 1;
//    [self.downLoadButton addTarget:self action:@selector(clickdownLoadButton:) forControlEvents:UIControlEventTouchUpInside];
//    [self.downSecondView addSubview:self.downLoadButton];
    
//    self.showPrograss = [[UILabel alloc] initWithFrame:CGRectMake(120, self.downSecondView.frame.size.height - 50, 50, 20)];
//    self.showPrograss.backgroundColor = [UIColor clearColor];
//    [self.downSecondView addSubview:self.showPrograss];
    
    
    
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.itemSize = CGSizeMake(WIDTH, (HEIGHT - 64)/2);
    flow.minimumLineSpacing = 0;
    flow.sectionInset = UIEdgeInsetsMake(0, 0, HEIGHT - 64 - (HEIGHT - 64)/2 - 60, 0);
    flow.scrollDirection = 1;
    self.collView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT - 64 - 60) collectionViewLayout:flow];
    self.collView.pagingEnabled = YES;
    self.collView.showsHorizontalScrollIndicator = NO;
    //    self.collView.indicatorStyle = 2;
    self.collView.delegate = self;
    self.collView.dataSource = self;
    self.collView.backgroundColor = [UIColor clearColor];
    self.collView.contentOffset = CGPointMake(WIDTH * self.movieIndexPath.row, 0);
    [self.collView registerClass:[MovieDetailCell class] forCellWithReuseIdentifier:MDcollReuse];
    [self.view addSubview:self.collView];
}

- (void)creatTopViewForDetail
{
    [super creatTopViewForDetail];
    self.rightBackView.image = [UIImage imageNamed:@"chakan"];
}
- (void)rightBuAction:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
#pragma mark -
#pragma mark 收藏按钮
- (void)clicksaveButton:(UIButton *)button
{
    CGFloat downX = self.collView.contentOffset.x;
    NSInteger downIndex = downX / WIDTH;
    VideoModel *model = self.movieDetaiArr[downIndex];
    if ([self.manager selectData:model.title EntityStyle:Save].count != 0) {
        SaveDaily *daily = [[self.manager selectData:model.title EntityStyle:Save] firstObject];
        [self.manager.managedObjectContext deleteObject:daily];
        [self.manager saveContext];
        [self.saveButton setImage:[UIImage imageNamed:@"shoucang"] forState:UIControlStateNormal];
    }else {
        [self.manager addCoreData:model EntityStyle:Save];
        [button setImage:[UIImage imageNamed:@"shoucang(1)"] forState:UIControlStateNormal];
    }
}
#pragma mark -
#pragma mark 下载按钮
//- (void)clickdownLoadButton:(UIButton *)button
//{
//    ASITool *asiTool = [ASITool shareASITool];
//    
//    CGFloat downX = self.collView.contentOffset.x;
//    NSInteger downIndex = downX / WIDTH;
//    DailyListModel *model = self.movieDetaiArr[downIndex];
//    if ([self.manager selectData:model.title EntityStyle:DownLoad].count != 0) {
//        //停止下载
//        [asiTool stopDownLoadWithName:model.title];
//        
//        SaveDaily *daily = [[self.manager selectData:model.title EntityStyle:DownLoad] firstObject];
//        [self.manager.managedObjectContext deleteObject:daily];
//        [self.manager saveContext];
//        [button setImage:[UIImage imageNamed:@"xiazai"] forState:UIControlStateNormal];
//        
//    }else {
//        [self.manager addCoreData:model EntityStyle:DownLoad];
//        [button setImage:[UIImage imageNamed:@"xiazai(1)"] forState:UIControlStateNormal];
//        //开始下载
//        [asiTool begainDownLoadWithUrl:model.playUrl name:model.title];
//    }
//}
//

#pragma mark -
#pragma mark 协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.movieDetaiArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MovieDetailCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:MDcollReuse forIndexPath:indexPath];
    VideoModel *model = self.movieDetaiArr[indexPath.row];
    [cell.detailImage sd_setImageWithURL:[NSURL URLWithString:model.coverForFeed] placeholderImage:[UIImage imageNamed:@"placehoder"]];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    PlayMovieVC *vc = [[PlayMovieVC alloc] init];
    vc.modalTransitionStyle = 2;
    vc.movieArr = self.movieDetaiArr;
    vc.index = indexPath.row;
    [self presentViewController:vc animated:YES completion:^{
        
    }];
    
    //    DailyListModel *model = self.movieDetaiArr[indexPath.row];
    //    NSURL *url = [NSURL URLWithString:model.playUrl];
    //    [self playMovieWith:url];
}

#pragma mark - 滑动展示图片覆盖效果
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat conX = scrollView.contentOffset.x;
    //轮播覆盖效果
    if (conX >= 0 && conX <= scrollView.contentSize.width - self.view.frame.size.width){
        //获取当前的index.row
        NSInteger currentIndex = conX / WIDTH;
        //相对的偏移量
        conX -= currentIndex * WIDTH;
        MovieDetailCell *currentCell = (MovieDetailCell *)[self.collView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:currentIndex inSection:0]];
        MovieDetailCell *nextCell = (MovieDetailCell *)[self.collView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:currentIndex + 1 inSection:0]];
        CGRect rect1 = currentCell.detailImage.frame;
        CGRect rect2 = nextCell.detailImage.frame;
        rect1.origin.x = conX * 4 / 5;
        rect2.origin.x = - (WIDTH - conX) * 4 / 5;
        currentCell.detailImage.frame = rect1;
        nextCell.detailImage.frame = rect2;
        
        //        UIImageView *aView = (UIImageView *)[self.view viewWithTag:1000 +currentIndex];
        //        aView.alpha = 1 - conX / WIDTH;
        
        currentCell.playView.alpha = 1 - 1.5 * conX / WIDTH;
        nextCell.playView.alpha = 1.5 * conX / WIDTH - 0.5;
    }
    //视图跟随
    if (scrollView.contentOffset.x <= 0) {
        CGRect rect = self.downBackView.frame;
        rect.origin.x = - scrollView.contentOffset.x;
        self.downBackView.frame = rect;
    }else if (scrollView.contentOffset.x >= (self.movieDetaiArr.count - 1) *WIDTH){
        CGRect rect = self.downBackView.frame;
        rect.origin.x = (self.movieDetaiArr.count - 1) * WIDTH - scrollView.contentOffset.x ;
        self.downBackView.frame = rect;
    }else{
        self.downBackView.frame = CGRectMake( 0, (HEIGHT - 64)/2 + 64, WIDTH, (HEIGHT - 64)/2);
    }
    
    //向右划
    
    UIImageView *aView = (UIImageView *)[self.view viewWithTag:1000];
    UIImageView *aView1 = (UIImageView *)[self.view viewWithTag:1001];
    
    if (scrollView.contentOffset.x > self.scrollerOffset) {
        if (conX != 0) {
            aView.alpha = 1 - (scrollView.contentOffset.x - self.scrollerOffset) / WIDTH;
            self.downSecondView.alpha = aView.alpha;
            aView1.alpha = 1;
        }
    }else if(scrollView.contentOffset.x < self.scrollerOffset){
        aView.alpha = 1 - (self.scrollerOffset - scrollView.contentOffset.x) / WIDTH;
        self.downSecondView.alpha = aView.alpha;
        aView1.alpha = 0;
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat downX = scrollView.contentOffset.x;
    NSInteger downIndex = downX / WIDTH;
    VideoModel *model = self.movieDetaiArr[downIndex];
    
    self.downTitleLabel.text = model.title;
    self.downTimeLabel.text = [NSString stringWithFormat:@"%@ / %@", model.category, model.duration];
    self.downDetailLabel.text = model.myDescription;
    self.downSecondView.alpha = 1;
    
    [self.saveButton setImage:[UIImage imageNamed:@"shoucang"] forState:UIControlStateNormal];
    if ([self.manager selectData:model.title EntityStyle:Save].count != 0) {
        [self.saveButton setImage:[UIImage imageNamed:@"shoucang(1)"] forState:UIControlStateNormal];
    }
    [self.downLoadButton setImage:[UIImage imageNamed:@"xiazai"] forState:UIControlStateNormal];
//    if ([self.manager selectData:model.title EntityStyle:DownLoad].count != 0) {
//        [self.downLoadButton setImage:[UIImage imageNamed:@"xiazai(1)"] forState:UIControlStateNormal];
//    }
    
    //========================
    UIImageView *aView = (UIImageView *)[self.view viewWithTag:1000];
    UIImageView *aView1 = (UIImageView *)[self.view viewWithTag:1001];
    UIImageView *aView2 = (UIImageView *)[self.view viewWithTag:1002];
    
    if (scrollView.contentOffset.x > self.scrollerOffset) {
        aView.image = aView1.image;
    }else if(scrollView.contentOffset.x < self.scrollerOffset){
        aView.image = aView2.image;
    }
    aView.alpha = 1;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.scrollerOffset = scrollView.contentOffset.x;
    NSInteger current = self.scrollerOffset / WIDTH;
    UIImageView *aView1 = (UIImageView *)[self.view viewWithTag:1001];
    UIImageView *aView2 = (UIImageView *)[self.view viewWithTag:1002];
    if (current + 1 < self.movieDetaiArr.count) {
        VideoModel *model = self.movieDetaiArr[current + 1];
        [aView1 sd_setImageWithURL:[NSURL URLWithString:model.coverBlurred] placeholderImage:[UIImage imageNamed:@"placehoder"]];
    }
    if (current > 0 ) {
        VideoModel *model = self.movieDetaiArr[current - 1];
        [aView2 sd_setImageWithURL:[NSURL URLWithString:model.coverBlurred] placeholderImage:[UIImage imageNamed:@"placehoder"]];
        aView2.alpha = 1;
    }
}

#pragma mark -
#pragma mark 添加手势
- (void)addGesture
{
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(backToLastPage)];
    [self.collView addGestureRecognizer:swipe];
    swipe.direction = UISwipeGestureRecognizerDirectionUp;
}
- (void)backToLastPage
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
